<?php
namespace App\Http\Controllers\Manage\Mall;

use App\Http\Controllers\Manage\CommonController;
use App\Http\Requests\ProductPostRequest;
use App\Model\Mall\Product;
use App\Model\Mall\ProductCategory;
use Illuminate\Support\Facades\DB;

class ProductController extends CommonController
{
    /**
     * 查看商品
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => '商品编号',
            'title' => '商品名称',
            'price' => '商品价格',
            'sale_price' => '促销价格',
            'create_time' => '发布时间',
            'status' => '状态',
        ];
        $viewData = [];
        $viewData['title'] = '商品管理';
        # 查询字段
        $viewData['field'] = $field;
        # 列表取值范围替换
        $viewData['range'] = [
            'status' =>[ 0 =>'下架', 1 => '上架']
        ];
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '发布新商品',
                'route' => route('manage.mall.product.resource.create')
            ]
        ];
        # 行表操作菜单
        $viewData['option_row'] = [
            'edit' => [
                'title' => '编辑',
                'route' => 'manage.mall.product.resource.edit'
            ],
            'eye' => [
                'title' => '上架',
                'route' => 'manage.mall.product.status',
                'where' => [
                    ['name' => 'status', 'condition' => '=', 'value' => '0']
                ]
            ],
            'eye-slash' => [
                'title' => '下架',
                'route' => 'manage.mall.product.status',
                'where' => [
                    ['name' => 'status', 'condition' => '=', 'value' => '1']
                ]
            ],
            'trash' => [
                'title' => '删除',
                'route' => 'manage.mall.product.resource.destroy'
            ]
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'method' => 'DELETE',
                'title' => '删除商品',
                'msg' => '确定要将该商品放入回收站吗'
            ],
        ];
        # 查询记录
        $product = Product::where('is_delete', 0);
        $viewData['list'] = $this->constraintSelectDB($product);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除商品
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $product = Product::find($id);
        $product->is_delete = 1;
        $product->update_user = $this->user['id'];
        $this->log(json_encode('manage:' . $this->user['id'] . ' remove product:' . $id . ' time:' . currentTime()), 'info', 'product_destroy');
        if ($product->save()) {
            return redirect()->back()->with('success', '商品删除成功!');
        }
        return redirect()->back()->with('error', '商品删除失败!');
    }

    /**
     * 创建商品页面
     * @return mixed
     */
    public function create()
    {
        $category = ProductCategory::keyName();
        # 表单元素
        $param = [];
        $param['title'] = [
            'name' => '商品名称',
            'type' => 'text',
            'col' => '12'
        ];
        $param['category_id'] = [
            'name' => '商品分类',
            'type' => 'select',
            'col' => '3',
            'range' => $category,
            'default' => '0:请选择分类'
        ];
        $param['price'] = [
            'name' => '商品价格',
            'type' => 'number',
            'col' => '3'
        ];
        $param['sale_price'] = [
            'name' => '促销价格',
            'type' => 'number',
            'col' => '3'
        ];
        $param['virtual_callback'] = [
            'name' => '虚拟商品自动发货地址',
            'type' => 'text',
            'col' => '12'
        ];
        $param['thumb'] = [
            'name' => '商品缩略预览图（建议256×256像素）',
            'type' => 'thumb',
            'col' => '3',
            'accept' => 'image',
            'ratio' => '1'
        ];
        foreach ($param as $key => $value) {
            $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '发布新商品';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.mall.product.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回商品列表',
                'type' => 'button',
                'route' => route('manage.mall.product.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     *
     * 创建商品页面
     *
     * @param ProductPostRequest $request
     * @return mixed
     */
    public function store(ProductPostRequest $request)
    {
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写商品名称');
        }
        # 检查商品分类是否存在
        $categoryID = $this->request->input('category_id');
        if ($categoryID == 0) {
            return redirect()->back()->with('error', '请选择商品分类');
        }
        if (!$this->request->has('price')) {
            return redirect()->back()->with('error', '请填写商品价格');
        }
        $thumb = null;
        if($this->request->has('thumb')) {
            $thumb = $this->request->input('thumb');
            $thumb = $this->uploadBase64Image($thumb, 'product_thumb');
            if (!$thumb) {
                return redirect()->back()->with('error', '商品预览图文件上传失败!');
            }
        }
        # 插入新数据
        $product = new Product();
        $product->category_id = $categoryID;
        $product->thumb = $thumb;
        $product->title = $this->request->input('title');
        $product->price = $this->request->input('price', 0);
        $product->sale_price = $this->request->input('sale_price', 0);
        $product->virtual_callback = $this->request->input('virtual_callback');
        $product->is_virtual = 1;
        $product->status = 1;
        $product->create_user = $this->user['id'];
        if ($product->save()) {
            # 创建成功后跳转到商品详细介绍编辑页
            return redirect()->route('manage.mall.product.resource.index')->with('success', '商品创建成功!');
        }
        return redirect()->back()->with('error', '商品创建失败!');
    }

    /**
     * 修改管理员信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $product = Product::find($id);
        $category = ProductCategory::keyName();
        # 表单元素
        $param = [];
        $param['title'] = [
            'name' => '商品名称',
            'type' => 'text',
            'col' => '12',
            'value' => $product->title
        ];
        $param['category_id'] = [
            'name' => '商品分类',
            'type' => 'select',
            'col' => '3',
            'range' => $category,
            'value' => $product->category_id
        ];
        $param['price'] = [
            'name' => '商品价格',
            'type' => 'number',
            'col' => '3',
            'value' => $product->price
        ];
        $param['sale_price'] = [
            'name' => '促销价格',
            'type' => 'number',
            'col' => '3',
            'value' => $product->pay_price
        ];
        $param['virtual_callback'] = [
            'name' => '虚拟商品自动发货地址',
            'type' => 'text',
            'col' => '12',
            'value' => $product->virtual_callback
        ];
        $thumb = ($product->thumb != null) ? $this->domain . $this->path['product_thumb'] . $product->thumb : null;
        $param['thumb'] = [
            'type' => 'thumb',
            'col' => '3',
            'name' => '商品缩略预览图（建议256×256像素）',
            'accept' => 'image',
            'value' => $thumb,
            'ratio' => '1',
        ];
        foreach ($param as $key => $value) {
            if ($this->request->old($key)) $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '修改商品信息';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.mall.product.resource.update', ['id' => $id]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回商品列表',
                'type' => 'button',
                'route' => route('manage.mall.product.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }

    /**
     *
     * 修改管理员信息操作
     *
     * @param ProductPostRequest $request
     * @param $id
     * @return mixed
     */
    public function update(ProductPostRequest $request, $id)
    {
        $product = Product::find($id);
        if (!$product) {
            return redirect()->back()->with('error', '商品编号不存在');
        }
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写商品名称');
        }
        # 检查商品分类是否存在
        $categoryID = $this->request->input('category_id');
        if ($categoryID == 0) {
            return redirect()->back()->with('error', '请选择商品分类');
        }
        if (!$this->request->has('price')) {
            return redirect()->back()->with('error', '请填写商品价格');
        }
        # 修改商品预览图
        $thumb = null;
        if ($this->request->has('thumb')) {
            $thumb = $this->request->input('thumb');
            $thumb = $this->uploadBase64Image($thumb, 'product_thumb');
            if (!$thumb) {
                return redirect()->back()->with('error', '商品预览图文件上传失败!');
            }
        }
        # 更新数据
        $product->title = $this->request->input('title');
        $product->price = $this->request->input('price', 0);
        $product->sale_price = $this->request->input('sale_price', 0);;
        $product->virtual_callback = $this->request->input('virtual_callback');
        if ($thumb) $product->thumb = $thumb;
        if ($product->save()) {
            return redirect()->route('manage.mall.product.resource.index')->with('success', '商品修改成功');
        }
        return redirect()->back()->with('error', '商品修改成功');
    }

    /**
     *
     * 商品上架下架
     *
     * @param $id
     * @return mixed
     */
    public function status($id)
    {
        $product = Product::find($id);
        if(!$product) {
            return redirect()->back()->with('error', '商品信息异常！');
        }
        $status = ($product->status == '1') ? '0' : '1';
        $msg = ($product->status == '1') ? '上架' : '下架';
        $product->status = $status;
        if(!$product->save()) {
            return redirect()->back()->with('error', '商品' . $msg . '失败！');
        }
        return redirect()->route('manage.mall.product.resource.index')->with('success', '商品' . $msg . '成功！');
    }

}
